const Axios = require('axios')
const appConfig = require('../../configs/app.config')
const path = require('path')
const sessionUrils = require('./session')
const apis = require(path.join(__dirname, '../apis'))
const baseUrl = appConfig.apis.domain

module.exports = function (ctx, next) {
    console.log('-------------proxy-----------------')
    const path = apis.getUrl(ctx.path)
    const apiItem = apis.getItem(ctx.path)
    const session = ctx.session

    if (apiItem.params.indexOf('token') !== -1 && !session.user) {
        ctx.body = {
            success: false,
            status: 'not logged in',
            message: `未登录或登录已过期，请重新登录！`
        }
        return
    }

    const moreParams = sessionUrils.getSessionUserParams(session, apiItem.params)

    const query = ctx.query
    const params = {
        ...moreParams,
        ...query,
        ...ctx.request.body
    }
    let _url = `${baseUrl}/${path}`
    console.log('post-url', _url)
    console.log('post-params', params)

    return Axios(_url, {
        data: params,
        method: ctx.method,
    }).then(res => {
        if (res.status === 200) {
            ctx.body = res.data
        } else {
            res.status = 500
            ctx.body = res.data
        }
    }).catch(err => {
        ctx.status = 500
        if (err.response) {
            ctx.status = err.response.status
            ctx.response.body = {
                status: ctx.status,
                message: `登录失败：${err.response.message}`
            }
            console.log(`登录失败：axios ${ctx.method} ${ctx.response.status}: ${_url}`)
        } else {
            ctx.body = {
                success: false,
                msg: '登录失败：未知错误'
            }
        }
    })
}

